import { IPageParam, IResPage } from '@/services';
import { times } from 'lodash';
import URI from 'urijs';

export const revertOssUrl = (url?: string) => {
  return url ? URI(url).pathname() : undefined;
};

export const revertICCUrl = (url?: string) => {
  return '/evo-apigw' + url;
};

export function mockApi<T>(
  data: T[],
): (params: IPageParam) => Promise<IResPage<T & { id: number }>> {
  return ({ page = 1, size = 10 }: IPageParam) =>
    Promise.resolve({
      code: 0,
      message: '',
      data: {
        pageData: times(10).map((item) => {
          return {
            ...data[item % data.length],
            id: (page - 1) * 10 + item + 1,
          };
        }),
        pagedInfo: {
          total: 1000,
          page: page,
          size: size,
        },
      },
    });
}

export const getParentKey = (value: string, tree: any[]) => {
  let parentKey: string;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item: any) => item.title?.indexOf(value) > -1)) {
        parentKey = node.id;
      } else if (getParentKey(value, node.children)) {
        parentKey = getParentKey(value, node.children);
      }
    }
  }
  return parentKey!;
};

export const emptyRender = (text: any) => {
  return text || '-';
};

export const getMonthArr = Array.from({ length: 12 }).map((_, i) => {
  if (i < 9) {
    return {
      label: '0' + Number(i + 1),
      value: '0' + Number(i + 1),
    };
  } else {
    return {
      label: i + 1,
      value: i + 1,
    };
  }
});
